package com.b2c.erp.controller.fahuo;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.b2c.erp.controller.CommonControllerUtils;
import com.b2c.interfaces.WmsUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.api.ApiResult;
import com.b2c.common.utils.DateUtil;
import com.b2c.entity.DataRow;
import com.b2c.entity.datacenter.DcShopEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.erp.DataConfigObject;
import com.b2c.interfaces.ShopService;
import com.b2c.interfaces.pdd.OrderPddService;

/**
 * 
 * 店铺订单确认Controller
 */
@RequestMapping("/fahuo")
@Controller
public class ShopOrderConfirmController {
    @Autowired
    private OrderPddService pddService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private WmsUserService manageUserService;
    private static Logger log = LoggerFactory.getLogger(ShopOrderConfirmController.class);
    /***
    * pdd待确认订单list
    * @param model
    * @param request
    * @return
    */
   @RequestMapping(value = "/wait_confirm_order_list_pdd", method = RequestMethod.GET)
   public String orderList(Model model, HttpServletRequest request) {
       Integer pageIndex = 1;
       Integer pageSize = DataConfigObject.getInstance().getPageSize();

       if (StringUtils.isEmpty(request.getParameter("page")) == false) {
           try {
               pageIndex = Integer.parseInt(request.getParameter("page"));
           } catch (Exception e) {
           }
       }
      
       Integer shopId = null;
       if(!StringUtils.isEmpty(request.getParameter("shopId"))){
           try{
            shopId = Integer.parseInt(request.getParameter("shopId"));
               model.addAttribute("shopId",shopId);
           }catch (Exception e){}
       }

       String orderNum = request.getParameter("orderNum");
       model.addAttribute("orderNum", orderNum);

       String pddGoodsId = request.getParameter("pddGoodsId");
       model.addAttribute("pddGoodsId", pddGoodsId);

      

       Integer startTime = 0;
       if (StringUtils.isEmpty(request.getParameter("startTime")) == false) {
           startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
           model.addAttribute("startTime", request.getParameter("startTime"));
       }

       Integer endTime = 0;
       if (StringUtils.isEmpty(request.getParameter("endTime")) == false) {
           endTime = DateUtil.dateTimeToStamp(request.getParameter("endTime") + " 23:59:59");
           model.addAttribute("endTime", request.getParameter("endTime"));
       }


       model.addAttribute("pageIndex", pageIndex);
       model.addAttribute("pageSize", pageSize);

       var result = pddService.getOrderListAndItem(pageIndex, pageSize,orderNum, null, shopId, startTime, endTime,0,pddGoodsId);

       model.addAttribute("list", result.getList());
       model.addAttribute("totalSize", result.getTotalSize());

       Integer userId = DataConfigObject.getInstance().getLoginUserId();
        //有权限的店铺列表
        List<DcShopEntity> shops = shopService.getShopListByUserId(userId,5);//type=5是拼多多
        model.addAttribute("shops", shops);


//       model.addAttribute("view", "pddordersend");
//       model.addAttribute("pView", "pdd");
       CommonControllerUtils.setViewKey(model,manageUserService,"pddorder");
       return "fahuo/wait_confirm_order_list_pdd";
   }

       /**
     * 订单批量确认发货
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pdd_order_confirm_batch", method = RequestMethod.POST)
    public ApiResult<Object> batchOrderSend( HttpServletRequest request,@RequestBody DataRow data ) {

        if(1==1) return new ApiResult<>(401, "未实现");

        String orderIds = data.getString("ids");
        if(StringUtils.isEmpty(orderIds)) return new ApiResult<>(401, "参数错误，缺少orderIds");
        int successCount = 0;
        int failCount =0;
        int isExistCount = 0;
        for (var oid : orderIds.split(",")) {
            try {
                Long orderId = Long.parseLong(oid);
                var order = pddService.getOrderDetailAndItemsById(orderId);
                log.info("/**********************订单状态判断" + order.getOrder_status() + "**********************/");
                if (order == null){
                    log.info("订单确认，未找到订单："+orderId);
                    failCount++;
                }else if (order.getAuditStatus().intValue() > 0){
                    isExistCount++;
                    log.info("订单确认，订单已经确认过了："+orderId);
                }else if(order.getRefund_status() != 1){
                    log.info("订单确认，订单售后中，不能操作："+orderId);
                    failCount++;
                }

                log.info("/**********************开始确认订单" + orderId + "**********************/");
                synchronized (this) {
                    //确认订单，加入到仓库系统待发货订单列表
                    ResultVo<Integer> result = pddService.orderConfirmAndJoinDeliveryQueueForPdd(orderId,null,null,null,null);

                    log.info("/**********************确认订单完成" + JSONObject.toJSONString(result) + "**********************/");
                    if(result.getCode() == EnumResultVo.SUCCESS.getIndex()){
                        successCount ++;
                    }else{
                        failCount++;
                    }
                }

            } catch (Exception e) {
                failCount++;
            }
            
        }

        String remark = "总共"+orderIds.split(",").length+"个订单，成功："+successCount+"失败："+failCount+"已处理过："+isExistCount;

        return new ApiResult<>(0,remark);
    }
}
